//
//  ComposeViewController.swift
//  weibo19
//
//  Created by Arvin on 15/11/19.
//  Copyright © 2015年 Arvin. All rights reserved.
//

import UIKit
import SnapKit
import MBProgressHUD

class ComposeViewController: UIViewController {
    @objc func pickerPicture() {
        picturePickerController.view.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view).offset(screenHeight * 0.4)
        }

        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    private lazy var keyBoardView: EmoticonKeyBoardView = EmoticonKeyBoardView {[weak self] (emoticon) -> () in
        self?.textView.setupText(emoticon)
    }
    
    
    @objc func pickerEmoticon() {
        textView.resignFirstResponder()
        textView.inputView = (textView.inputView == nil ? keyBoardView : nil)
        textView.becomeFirstResponder()
        
    }
    
    @objc func back() {
        navigationController?.dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc func sendMessage() {

        var params = [String: AnyObject]()
        params["access_token"] = UserAccountViewModel().account?.access_token

        // 只上传文本接口 https://api.weibo.com/2/statuses/update.json
        // 上传图片和文本的接口 https://upload.api.weibo.com/2/statuses/upload.json
        
        // 获取图片 Hello World!!!!
        if picturePickerController.pictures.count >= 1 {
            let image = picturePickerController.pictures.first
            let data = UIImagePNGRepresentation(image!)
            let urlStr = "https://upload.api.weibo.com/2/statuses/upload.json"
            params["status"] = textView.text
            NetworkTools().uploadText(urlStr, params: params, imageData: data!) { (result, error) -> () in
                if error != nil {
                    MBProgressHUD.showError(errorMessage)
                    return
                }
                MBProgressHUD.showSuccess("上传成功!")
                self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
            }
        } else {

            let urlStr = "https://api.weibo.com/2/statuses/update.json"
            params["status"] = textView.fullText()
            NetworkTools().uploadText(urlStr, params: params, imageData: nil) { (result, error) -> () in
                if error != nil {
                    MBProgressHUD.showError(errorMessage)
                    return
                }
                MBProgressHUD.showSuccess("上传成功!")
                self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
            }
 
        }
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardPopup:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        setupUI()
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    @objc private func keyboardPopup(noti: NSNotification) {
        
        let duration = noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! Double
        let h = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        // 动画曲线值
        let curve = noti.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! Int
        
        let bottomMargin = -screenHeight + h.origin.y
        
        self.toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(bottomMargin)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            //设自动画曲线值 如果设置了这个值 为7 动画持续时间失效
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
                self.view.layoutIfNeeded()
        
        }
    }
    
    private func setupUI() {
        
        view.addSubview(textView)
        textView.addSubview(label)
        view.addSubview(toolBar)
        setupItems()
        textView.becomeFirstResponder()
        // 添加控制器
        addChildViewController(picturePickerController)
        let picturePickerView = picturePickerController.view
        view.addSubview(picturePickerView)
        
        // 注意: 这段代码要放在picturePicker后面才能在它上面
        view.bringSubviewToFront(toolBar)

        view.backgroundColor = UIColor.whiteColor()
        navigationItem.leftBarButtonItem = letfItem
        navigationItem.rightBarButtonItem = rightItem
        rightItem.enabled = false
        
        let titleView = UIView(frame: CGRectMake(0, 0, 200, 40))
        // 注意: 直接设置item 前面不要加控制器
        navigationItem.titleView = titleView
        let titleLabel = UILabel(title: "发微博", size: UIFont.systemFontOfSize(17), margin: 0)
        titleLabel.textAlignment = NSTextAlignment.Center
        let nameLabel = UILabel(title: UserAccountViewModel().account?.name ?? "", size: UIFont.systemFontOfSize(14), margin: 0)
        nameLabel.textAlignment = NSTextAlignment.Center
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(titleView)
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleLabel.snp_bottom)
            make.left.right.equalTo(titleView)
        }
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(view)
            make.height.equalTo(view.bounds.height / 3)
        }
        
        label.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(10)
            make.left.equalTo(textView.snp_left).offset(14)
        }
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(40)
        }
        
        picturePickerView.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(view)
        }
    }
    
    private func setupItems() {
        var items = [UIBarButtonItem]()
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "pickerPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName":"pickerEmoticon"],
            ["imageName": "compose_camerabutton_background"]]
        
        for dict in itemSettings {
            let item = UIBarButtonItem(image: dict["imageName"]!, target: self, actionName: dict["actionName"])
            items.append(item)
            let FlexibleItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            items.append(FlexibleItem)
        }
        items.removeLast()
        toolBar.items = items
    }

    private lazy var letfItem: UIBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "back")
    
    private lazy var rightItem: UIBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "sendMessage")
    private lazy var textView: UITextView = {
        let text = UITextView()
        text.showsVerticalScrollIndicator = false
        text.textColor = UIColor.darkGrayColor()
        text.font = UIFont.systemFontOfSize(18)
        // 设置键盘消失模式
        text.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        text.alwaysBounceVertical = true
        text.delegate = self
        text.textContainerInset = UIEdgeInsetsMake(8, 10, 10, 10)
        return text
    }()
    
    private lazy var label: UILabel = {
        let l = UILabel(title: "分享新鲜事...", size: UIFont.systemFontOfSize(18), margin: 0)
        l.textColor = UIColor(white: 0.7, alpha: 1.0)
        return l
    }()
    
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    private lazy var picturePickerController: PicturePickerViewController = PicturePickerViewController()
}

extension ComposeViewController: UITextViewDelegate {
    func textViewDidChangeSelection(textView: UITextView) {
        rightItem.enabled = textView.hasText()
        label.hidden = textView.hasText()
        
//        print(textView.attributedText)
    }
}
